var refparam = {};
var myParams = {};
$(document).ready(function () {
    var codeId = app.getUrlParam("codeId");//页面的ID
    var value = app.getUrlParam("value");//子查询的值
    var index = app.getUrlParam("index");//子查询页面第几个查询条件
    var defaultParam = undefined;//父页面的查询条件
    var paramStr = localStorage.getItem("paramStr");//查询条件
    var treeDefault = {};
    localStorage.removeItem("paramStr");
    if (paramStr && paramStr.trim() != '') {
        defaultParam = JSON.parse(paramStr)
    }
    var btn = '<div class="form-group"><div class="col-sm-12 text-center"><button class="btn btn-primary buttonColor btnSize" type="button" id="btnQuery">查询</button><button class="btn btn-primary buttonColor btnSize" type="button" id="resetBtn">重置</button></div></div>';
    var formElement = '';
    myParams.codeId = codeId;
    refparam = myParams;
    //列表集合
    var columns = [{
        checkbox: true,
        footerFormatter: function () {
            return "<div class='text-right text-bold' >统计</div>";
        }

    }];
    var resultItem = app.callAjaxPostSync('../../../../api/baseCommonqueryController/listCommonQueryTempleteData', {codeId: codeId});
    if (!resultItem.success) {
        layer.alert("页面配置参数有误");
        return;
    }
    //查询条件集合
    var conditions = resultItem.data.conditions;
    //列表展示集合
    var results = resultItem.data.results;
    //表头数据
    var head = resultItem.data.head;
    //是否需要统计
    var isGroup = resultItem.data.isGroup;
    var pageTitle = head.NAME;
    //sql脚本
    var sql = '';
    if(!isNaN(index)){
        if(conditions){
            if(conditions.length<parseInt(index)){
                layer.alert("页面配置参数有误");
                return;
            }else {
                myParams[conditions[parseInt(index)-1].REPLACEFIELD]=value?value:"";
            }
        }else {
            layer.alert("页面配置参数有误");
            return;
        }
    }
    if (head) {
        sql = head.SQLSCRIPT;
        myParams.sql = head.SQLSCRIPT;
    }
    if (results) {
        for (var i = 0; i < results.length; i++) {
            var resultItem = results[i];
            var itemColum = {
                field: resultItem.itemField,
                halign: 'center',
                title: resultItem.NAME1
            }
            if (resultItem.ISGROUP) {
                if (resultItem.ISGROUP == 1) {
                    //汇总
                    itemColum.footerFormatter = getFucntion(resultItem.itemField, '1');
                }
                if (resultItem.ISGROUP == 2) {
                    //总记录
                    itemColum.footerFormatter = getFucntion(resultItem.itemField, '2');
                }
                if (resultItem.ISGROUP == 3) {
                    //最大值
                    itemColum.footerFormatter = getFucntion(resultItem.itemField, '3');
                }
                if (resultItem.ISGROUP == 4) {
                    //最小值
                    itemColum.footerFormatter = getFucntion(resultItem.itemField, '4');
                }
            }
            if (resultItem.NEXTQUERY && resultItem.NEXTQUERY.trim()) {
                var nextQueryList = resultItem.NEXTQUERY.split(";");
                //如果有子查询,第一个参数为跳转页面的ID，第二个参数为第几列的值，第三个参数为跳转页面第几个输入框，第四个参数为跳转页面的名字
                itemColum.formatter = function (value, row, index) {

                    var subindex = nextQueryList[1] - 1;//子查询中的第二个参数，即第几列
                    var itemElement = 'field' + subindex;
                    var itemValue = row[itemElement];
                    var nextName = nextQueryList[3];
                    return "<a name=\"field" + i + "\" style=\"color: blue;text-decoration:underline;\" href=\"javascript:void(0);\" onclick=\"openLinkPage('" + nextQueryList[0] + "','" + itemValue + "','" + nextQueryList[2] + "','" + nextName + "');\">" + value + "</a>";
                };
            }
            columns.push(itemColum);
        }
    }
    //下拉框集合
    var selectComponentList = [];
    //日期框集合
    var dataComponentList = [];
    //树形下拉框集合
    var treeComponentList = [];
    if (conditions) {
        var n = 1;
        for (var j = 0; j < conditions.length; j++) {
            var conditionItem = conditions[j];
            var itemVueModel = "myParams." + conditionItem.REPLACEFIELD;
            var itemName = conditionItem.REPLACEFIELD;
            var itemLabel = conditionItem.FIELDNAME;
            var defaultvalue = myParams[itemName]?'':conditionItem.DEFAULTVALUE;
            var required = conditionItem.ALLOWLANK == '1' ? true : false;
            if (defaultParam) {
                defaultvalue = defaultParam[itemName];
            }
            if (index != undefined && j == index - 1) {
                defaultvalue = value;
            }
            //如果是3的倍数则换行，既重新创建一个form—group
            if (j % 3 == 0) {
                n = 1;
                formElement += '<div class="form-group">'
            }
            //树形下拉框
            if (conditionItem.COMPONENTNAME == 7) {
                if (conditionItem.INITVALUE) {
                    treeDefault = JSON.parse(conditionItem.INITVALUE);
                }
                treeComponentList.push({
                    id: itemName,
                    jsonStr: conditionItem.INITVALUE,
                    dept: myParams.conditionC
                });
            }
            if (conditionItem.COMPONENTNAME == 3) {
                //下拉框
                selectComponentList.push({
                    id: itemName,
                    sql: conditionItem.INITVALUE
                });
            }
            if (conditionItem.COMPONENTNAME == 5) {
                //日期框
                dataComponentList.push({
                    id: itemName
                });
                if (defaultvalue) {
                    if (!(defaultParam && defaultParam[itemName])) {
                        var param = {};
                        //0表示当前日期
                        param.num = parseInt(defaultvalue);
                        if (defaultvalue == '0') {
                            param.MODE = "NOW";
                        }
                        //W表示周
                        if (defaultvalue.indexOf("W") != -1) {
                            param.MODE = "W";
                        }
                        //D表示日
                        if (defaultvalue.indexOf("D") != -1) {
                            param.MODE = "D";
                        }
                        //M表示月
                        if (defaultvalue.indexOf("M") != -1) {
                            param.MODE = "M";
                        }
                        //Y表示年
                        if (defaultvalue.indexOf("Y") != -1) {
                            param.MODE = "Y";
                        }
                        var result = app.callAjaxPostSync("../../../../api/baseCommonqueryController/caculateDate", param);
                        if (result && result.success == true) {
                            defaultvalue = result.data;
                        }
                    }
                }
            }
            //添加组件
            formElement += getElement({
                COMPONENTNAME: parseInt(conditionItem.COMPONENTNAME),
                defaultvalue: defaultvalue,
                itemName: itemName,
                itemLabel: itemLabel,
                itemVueModel: itemVueModel,
                required: required
            });
            //如果当前组件为3的倍数则换行
            if (n % 3 == 0 || j == conditions.length - 1) {
                formElement += '</div>'
            }
            n++;

        }
        //添加查询按钮
        $('#queryForm').append(formElement).append(btn);
    }
    var queryConditions = new Vue({
        el: '#queryForm',
        data: {
            myParams: myParams
        }
    });
    for (var m = 0; m < selectComponentList.length; m++) {
        var selectComponentItem = selectComponentList[m];
        initSelecct(selectComponentItem.id, selectComponentItem.sql);
    }
    for (var k = 0; k < dataComponentList.length; k++) {
        var dataComponentItem = dataComponentList[k];
        initDate(dataComponentItem.id, dataComponentItem.id);
    }
    for (var t = 0; t < treeComponentList.length; t++) {
        var treeComponentItem = treeComponentList[t];
        initTreeSelect(treeComponentItem.id, treeComponentItem.jsonStr, treeComponentItem.dept);
    }
    var me = $(this);
    var queryTime = 0;
    //存储主页面点击的行信息
    var curRow = {};

    /********************表格的初始化操作在此进行 ---- 实例化Grid ************************/
    var grid = $("#dataGrid").bootstrapTable({
        columns: columns,
        sortable: true,//是否可以排序，每一列都可以进行指定
        url: "../../../../api/baseCommonqueryController/selectAllDataByTemplete",//加载时调用的后台连接
        undefinedText: '',//字段值为undefine时显示的内容
        showRefresh: false,//是否显示刷新按钮
        showColumns: false,//是否显示列头
        showFooter: isGroup,
        striped: true,//是否显示表格线
        exportDataType: "all", //导出的数据类型
        exportTypes: ['excel'],//导出文件类型
        iconSize: "outline",//icon图标的显示方式
        toolbar: "#grdToolbar",//绑定表格的操作栏，就是新增、修改、删除按钮所在div的ID
        icons: {
            refresh: "glyphicon-repeat",
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list"
        },
        clickToSelect: false,
        pagination: true,//是否分页
        sidePagination: "server", // 表示分页时进行服务端请求
        method: 'post',//请求方法[post/get]
        dataField: 'data',
        pageNumber: 1,//页面分页的初始页码
        pageSize: 10,//每页显示数量(暂定每页10条，请暂勿修改，保持统一)
        pageList: [5, 10, 25, 50, 100],//每页显示的可选数量
        queryParamsType: "undefined",

        //查询参数配置
        queryParams: function (params) {
            var pIndex, myTotal;
            if (queryTime === 0) {
                pIndex = 1;
                myTotal = -1;
                queryTime++;
            }
            else {
                pIndex = params.pageNumber;
                myTotal = this.totalRows;
            }

            return {
                limit: params.pageSize,
                page: pIndex,
                allcount: myTotal,
                data: queryConditions.myParams,
                sortName: params.sortName,
                sortOrder: params.sortOrder
            }
        },

        //排序事件
        onSort: function (name, order) {
            grid.queryData();
        },
        onClickRow: function (row, $element) {
            curRow = row;
        },
        //数据加载完毕事件
        onLoadSuccess: function (result) {
            $('.fixed-table-footer tr').clone().appendTo('#dataGrid tbody');
            $('.fixed-table-footer').hide();
            var tdList = $('tbody >tr').has('div').children();
            if (tdList && tdList.length > 0) {
                for (var i = 1; i < tdList.length; i++) {
                    var tdValue = tdList.eq(i).children().eq(0).text();
                    tdList.eq(i).children().remove();
                    tdList.eq(i).text(tdValue);
                }
            }
        }
    });

    /* 数据查询 */
    grid.queryData = function () {
        queryTime = 0;
        this.bootstrapTable('refresh', {
            silent: false
        });
    };

    /* 查询按钮点击 */
    $('#btnQuery').click(function () {
        if (!$("#queryForm").valid()) {
            return;
        }
        grid.queryData();
    });

    /*重置按钮*/
    $('#resetBtn').click(function () {
        $('#queryForm').find("input")
            .not(':button, :submit, :reset, :hidden')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');
        for (var key in myParams) {
            if (!(key == 'codeId' || key == 'sql')) {
                myParams[key] = '';
            }
        }
        queryConditions.myParams = myParams;
    });


    $('#export').click(function () {
        app.callAjaxPost('../../../../api/baseCommonqueryController/export', queryConditions.myParams, function (result) {
            if (result.success) {
                layer.alert(result.message, {icon: 6});
                window.location.href = "../../../../api/baseCommonqueryController/downloadTmp?filename=" + result.data.tmp_file_name + "&downloadname=" + head.NAME + ".xls";
            } else {
                layer.alert(result.message, {icon: 5});
            }
        }, this);
    })
//深度克隆
    function deepClone(obj) {
        var result, oClass = isClass(obj);
        //确定result的类型
        if (oClass === "Object") {
            result = {};
        } else if (oClass === "Array") {
            result = [];
        } else {
            return obj;
        }
        for (key in obj) {
            var copy = obj[key];
            if (isClass(copy) == "Object") {
                result[key] = arguments.callee(copy);//递归调用
            } else if (isClass(copy) == "Array") {
                result[key] = arguments.callee(copy);
            } else {
                result[key] = obj[key];
            }
        }
        return result;
    }

//初始化下拉框的值
    function initSelecct(el, sql) {
        $P.initDropdown($('#' + el), {sql: sql}, {
                idField: 'id',
                keyField: 'word',
                effectiveFields: ['word'],
                defaultValue: myParams[el]
            }
            , function (datas, e) {
                myParams[el] = datas["id"];
                if (sql.indexOf('跨贸') != -1 && treeComponentList.length > 0) {
                    $("#conditionF").bsSuggest("destroy");
                    $("#conditionF").val('');
                    myParams.conditionF = '';
                    var param = {};
                    param.dept = datas["id"];
                    param.type = treeDefault.type;
                    $P.initDropdown($('#conditionF'), param, {
                            idField: 'id',
                            keyField: 'word',
                            effectiveFields: ['word'],
                            defaultValue: myParams.conditionF
                        }
                        , function (datas, e) {
                            myParams.conditionF = datas["id"];
                        }, '../../../../api/baseCommonqueryController/listGoodsTypesForSelect');

                }
            }, '../../../../api/baseCommonqueryController/getSelectOption');
    }

    //初始化日期控件
    function initDate(el, field) {
        //初始化日期输入框
        laydate({
            elem: '#' + el,
            choose: function (datas) {
                myParams[field] = datas;
            }
        });
    }

    function initTreeSelect(el, jsonStr, dept) {
        var param = {};
        if (dept) {
            param.dept = dept;
            param.type = treeDefault.type;
        }
        $P.initDropdown($('#' + el), param, {
                idField: 'id',
                keyField: 'word',
                effectiveFields: ['word'],
                defaultValue: myParams[el]
            }
            , function (datas, e) {
                myParams[el] = datas["id"];
            }, '../../../../api/baseCommonqueryController/listGoodsTypesForSelect');
    }

//返回传递给他的任意对象的类
    function isClass(o) {
        if (o === null) return "Null";
        if (o === undefined) return "Undefined";
        return Object.prototype.toString.call(o).slice(8, -1);
    }
});
/**
 * 点击超链接打开子查询页面
 * @param pageId 页面的ID
 * @param value 自查询的值
 * @param index 第几个输入框
 * @param name 页面名字
 *  @param paramStr 查询参数
 */
function openLinkPage(pageId, value, index, name) {
    var paramstr = JSON.stringify(refparam);
    localStorage.setItem("paramStr", paramstr);
    var name = '';
    var result = app.callAjaxPostSync('../../../../api/baseCommonqueryController/getNameByPageId', pageId);
    if (result.success) {
        name = result.data;
    } else {
        layer.alert("子查询配置参数有误");
        return;
    }
    openNewTab("../system/commonquery/commonqueryTempleteMainForGoods.html?codeId=" + pageId + "&value=" + value + "&index=" + index, name);
}
//深度克隆
function deepClone(obj) {
    var result, oClass = isClass(obj);
    //确定result的类型
    if (oClass === "Object") {
        result = {};
    } else if (oClass === "Array") {
        result = [];
    } else {
        return obj;
    }
    for (key in obj) {
        var copy = obj[key];
        if (isClass(copy) == "Object") {
            result[key] = arguments.callee(copy);//递归调用
        } else if (isClass(copy) == "Array") {
            result[key] = arguments.callee(copy);
        } else {
            result[key] = obj[key];
        }
    }
    return result;
}
function getFucntion(name, type) {
    return function (value) {
        var count = 0;
        if (type == 2) {
            count = value.length;
        } else {
            for (var t in value) {
                if (type == 1) {
                    count = count + Number(value[t][name]);
                }
                if (type == 3) {
                    count = Number(value[t][name]) > count ? Number(value[t][name]) : count;
                }
                if (type == 4) {
                    count = Number(value[t][name]) < count ? Number(value[t][name]) : count;
                }
            }
        }
        var returnStr = count.toFixed(5) * 1;
        return returnStr == 0 ? "0" : returnStr;
    }
}
//根据组件编号获取组件
function getElement(config) {
    var str = '';
    switch (config.COMPONENTNAME) {
        //文本框
        case 1:
            str = str.concat('<div class="col-sm-4"><label class="col-sm-4 control-label">', config.itemLabel, '：</label><div class="col-sm-8"><input type="text" name="', config.itemName, '"v-model="', config.itemVueModel, '" class="form-control"', config.required ? ' required><span class="required">*</span></div></div>' : '></div></div>');
            break;
        case 2:
            break;
        case 3:
            str = str.concat('<div class="col-sm-4"><label class="col-sm-4 control-label">', config.itemLabel, '：</label><div class="col-sm-8"><div class="input-group"><input type="text" name="', config.itemName, '" :data-id="', config.itemVueModel, '" id="', config.itemName, '" class="form-control"', config.required ? ' required><div class="input-group-btn"><button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right" role="menu"></ul></div></div><span class="required2">*</span></div></div>' : '><div class="input-group-btn"><button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right" role="menu"></ul></div></div></div></div>');
            break;
        case 4:
            break;
        case 5:
            str = str.concat('<div class="col-sm-4"><label class="col-sm-4 control-label">', config.itemLabel, '：</label><div class="col-sm-8"><input type="text" v-model="', config.itemVueModel, '" name="', config.itemName, '" id="', config.itemName, '" class="form-control"', config.required ? ' required><span class="required">*</span></div></div>' : '></div></div>');
            break;
        case 6:
            break;
        //商品树下拉
        case 7:
            str = str.concat('<div class="col-sm-4"><label for="SORT" class="col-sm-4 control-label ">', config.itemLabel, ': </label><div class="col-sm-8 "><div class="input-group"><input type="text" class="form-control"  name="', config.itemName, '" id="', config.itemName, config.required ? '" required/><div class="input-group-btn"><button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right" role="menu"></ul></div></div><span class="required2">*</span></div></div>' : '"/><div class="input-group-btn"><button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button><ul class="dropdown-menu dropdown-menu-right" role="menu"></ul></div></div></div></div>');
            break;
    }
    if (config.defaultvalue) {
        myParams[config.itemName] = config.defaultvalue;
    }
    return str;
}
